<?php

namespace Fluency\Web\Routing;

use Fluency\Web\Http\Request;
use Fluency\Web\RequestDispatcher;

/**
 * A router that appends an initially specified string (which defaults to "index") to URLs and
 * treat them as action names. For example, an empty URL would map to the action "index", and the
 * URL "posts" would map to "posts/index". However, these actions are checked for existence, and
 * the request not returned if the composed action name does not resolve to any action.
 *
 * @package Fluency\Web\Routing
 * @author  Ignas Rudaitis
 * @since   1.0
 */
class IndexRouter implements Router
{
    private $dispatcher;
    private $baseActionName;

    /**
     * The constructor.
     *
     * @param Fluency\Web\RequestDispatcher $dispatcher the dispatcher to associate requests with
     * @param string $baseActionName a string to append to the URLs
     */
    public function __construct(RequestDispatcher $dispatcher, $baseActionName = "index")
    {
        $this->dispatcher = $dispatcher;
        $this->baseActionName = $baseActionName;
    }

    /**
     * @see Fluency\Web\Routing\Router::query()
     *
     * @param string $url
     * @return Fluency\Web\Http\Request|null
     */
    public function query($url)
    {
        $url = str_replace("//", "/", trim($url, "/"));
        $action = empty($url) ? $this->baseActionName : "{$url}/{$this->baseActionName}";
        $request = $this->dispatcher->createRequest()->forAction($action);
        if ($request->isExecutable()) {
            return $request;
        }
    }
}
